package com.cgycms.weblogserver.netty;

import com.alibaba.fastjson.JSON;
import com.cgycms.weblogcommon.model.WebLogMeta;
import com.cgycms.weblogserver.websocket.WebSocketServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @ClassName : ServerChannelHandlerAdapter
 * @Description : 接收客户端消息
 * @Author : cgy
 * @Date: 2020-09-11 15:45
 */
@Component
@ChannelHandler.Sharable
public class ServerChannelHandlerAdapter extends SimpleChannelInboundHandler<String> {

    private Logger log = LoggerFactory.getLogger(ServerChannelHandlerAdapter.class);


    @Override
    public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        //暂时没有好的解决办法，先替换掉吧
        msg = msg.replace("\\u0000", "").replace("0000", "");
        WebLogMeta invokeMeta = JSON.parseObject(msg, WebLogMeta.class);
        WebSocketServer.sendInfo(invokeMeta);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        log.warn("客户端地址：{}:{} 下线!", clientIp, ipSocket.getPort());

    }

}
